<?php declare(strict_types=1);

namespace app\home\controller;

use app\home\Diluma;
use app\common\service\MsgService;
use think\facade\Queue;

class Msg extends Diluma
{
    /**
     * 客户留言
     * @return void
     */
    public function msg()
    {
        $area = $this->request->param('area', '');
        $area_num = $this->request->param('area_num', 0);
        $username = $this->request->param('username', '', 'strip_tags');
        $contact = $this->request->param('contact', '', 'strip_tags');
        $type_name = $this->request->param('type_name', '', 'strip_tags');
        $remarks = $this->request->param('remarks', '', 'strip_tags');
        if (!$username) {
            return json(['code'=>1, 'msg'=>'请留下您的称呼']);
        }
        $phone = preg_match('/^1[3-9]\d{9}$/', $contact);
        $email = preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $contact);
        if (!($phone || $email)) {
            return json(['code'=>1, 'msg'=>'联系方式只能是手机或邮箱']);
        }
        $message = new MsgService();
        // 一天只能提交三次
        $count = $message->getMessageCount(['contact' => $contact]);
        if ($count > 3) {
            return json(['code'=>1, 'msg'=>'您今天已经留言了多次，要不明天再试试']);
        }
        $ip = get_client_ip();
        $data = [
            'area' => $area,
            'area_num' => $area_num,
            'username' => $username,
            'contact' => $contact,
            'remarks' => $remarks ?? '',
            'type_name' => $type_name,
            'ip' => $ip,
            'ip_address' => ipToAddress($ip)
        ];
        if ($message->updateOrInsert($data)) {
            // 异步处理任务
            Queue::push('app\job\Msg', $data, 'default');
            return json(['code'=>0, 'msg'=>'提交成功，<strong>八方筑装饰</strong>将尽快联系您']);
        } else {
            return json(['code'=>1, 'msg'=>'提交失败，请稍后再试！']);
        }
    }
}